package servlet.wxpay;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import entity.Order;
import service.OrderService;
import service.impl.OrderServiceImpl;
import servlet.wxpay.sdk.MyConfig;
import servlet.wxpay.sdk.WXPay;
import servlet.wxpay.sdk.WXPayUtil;

public class WxPayNotifyServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private OrderService orderService = new OrderServiceImpl();
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		try {
			String notifyData = "...."; // 支付结果通知的xml格式数据
			
			//1.从request获取XML流，转化成为MAP数据
            InputStream inputStream = request.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            StringBuffer sb = new StringBuffer();
            String temp;
            while ((temp = reader.readLine()) != null) {
                sb.append(temp);
            }
            reader.close();
            inputStream.close();
            
            notifyData = sb.toString();
			
			MyConfig config = new MyConfig();
			WXPay wxpay = new WXPay(config);

			Map<String, String> notifyMap = WXPayUtil.xmlToMap(notifyData);  // 转换成map

			if (wxpay.isResponseSignatureValid(notifyMap)) {
			    // 签名正确
			    // 进行处理。
			    // 注意特殊情况：订单已经退款，但收到了支付结果成功的通知，不应把商户侧订单状态从退款改成支付成功
				
				if ("SUCCESS".equals(notifyMap.get("return_code")) && "SUCCESS".equals(notifyMap.get("return_code"))) {
					
					Order order = orderService.findByOrderNO(notifyMap.get("out_trade_no"));
					
					double total_fee = Double.parseDouble(notifyMap.get("total_fee"))/100;
					
					if (order!=null && order.getStatus()==0 && order.getAmount()==total_fee) {
						order.setPayType(2);
						order.setStatus(1);
						order.setTrade_no(notifyMap.get("transaction_id"));
						orderService.updateStatus(order);
					}
				}
				response.getWriter().write("<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>");
			}else {
			    // 签名错误，如果数据里没有sign字段，也认为是签名错误
				response.getWriter().write("<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[签名失败]]></return_msg></xml>");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
